using System;
using System.Configuration;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;

namespace ApiScanner.Core
{
	[Serializable]
	public class SerializableConfigurationElement: ConfigurationElement, IXmlSerializable
	{
		public virtual string ConfigurationElementName {get { throw new NotImplementedException();}}

		internal void Deserialize(XmlReader reader)
		{
			base.DeserializeElement(reader, false);
		}

		public void Serialize(XmlWriter writer, bool serializeCollectionKey)
		{
			SerializeElement(writer, serializeCollectionKey);
		}

		protected override bool SerializeElement(XmlWriter writer, bool serializeCollectionKey)
		{
			if (writer == null) return true;

			return base.SerializeElement(writer, serializeCollectionKey);
		}

		protected override bool SerializeToXmlElement(XmlWriter writer, string elementName)
		{
			return base.SerializeToXmlElement(writer, ConfigurationElementName);
		}

		
		///<summary>
		///This property is reserved, apply the <see cref="T:System.Xml.Serialization.XmlSchemaProviderAttribute"></see> to the class instead. 
		///</summary>
		///
		///<returns>
		///An <see cref="T:System.Xml.Schema.XmlSchema"></see> that describes the XML representation of the object that is produced by the <see cref="M:System.Xml.Serialization.IXmlSerializable.WriteXml(System.Xml.XmlWriter)"></see> method and consumed by the <see cref="M:System.Xml.Serialization.IXmlSerializable.ReadXml(System.Xml.XmlReader)"></see> method.
		///</returns>
		///
		XmlSchema IXmlSerializable.GetSchema()
		{
			return null;
		}

		///<summary>
		///Generates an object from its XML representation.
		///</summary>
		///
		///<param name="reader">The <see cref="T:System.Xml.XmlReader"></see> stream from which the object is deserialized. </param>
		void IXmlSerializable.ReadXml(XmlReader reader)
		{
			if (!reader.IsStartElement(ConfigurationElementName))
			{
				// After sending the ConfigurationElementName through a WebService the element to deserialize is not the root anymore, instead it is child of the root node. The following line move the reader to this child.
				reader.ReadStartElement();
				if (!reader.IsStartElement(ConfigurationElementName))
				{
					throw new ConfigurationErrorsException(string.Format("Unexpected element node {0}. Expected element was {1}.", reader.LocalName, ConfigurationElementName), reader);
				}
			}
			DeserializeElement(reader, false);
		}

		///<summary>
		///Converts an object into its XML representation.
		///</summary>
		///
		///<param name="writer">The <see cref="T:System.Xml.XmlWriter"></see> stream to which the object is serialized. </param>
		void IXmlSerializable.WriteXml(XmlWriter writer)
		{
			writer.WriteStartElement(ConfigurationElementName);
			SerializeElement(writer, false);
			writer.WriteEndElement();
		}

	}
}
